package com.yuan.view;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;

import java.util.Collections;
import java.util.HashMap;


public final class JsonHelper {

    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static {
        OBJECT_MAPPER
                .registerModule(new ParameterNamesModule())
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule());
    }

    private JsonHelper() {

    }

    public static String toJSON(Object object) {
        if (object == null) return "{}";

        try {
            String JSON = OBJECT_MAPPER.writeValueAsString(object);
            return JSON;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }

    public static <T> T toBean(String json, Class<T> clazz) {
        try {
            T bean = OBJECT_MAPPER.readValue(json, clazz);
            return bean;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String json = toJSON(Collections.singletonMap("jackson", "json"));
        System.out.println("json = " + json);

        HashMap<String, String> hashMap = toBean(" {\"jackson\":\"json\"}", HashMap.class);
        System.out.println(hashMap);
    }


}
